<?php

namespace app\api\controller\sharing;

use app\api\controller\Controller;
use app\api\model\Setting as SettingModel;
use app\api\model\sharing\ActiveUsers;
use app\api\model\sharing\Order as OrderModel;
use app\api\model\User;
use app\api\model\user\BalanceLog;
use app\api\service\sharing\order\Checkout as CheckoutModel;
use app\api\validate\sharing\order\Checkout as CheckoutValidate;

use app\common\enum\OrderType as OrderTypeEnum;
use app\common\enum\order\PayType as PayTypeEnum;
use app\common\model\sharing\Active;
use app\common\model\sharing\RedBagLog;
use app\common\model\sharing\UserRedBag;
use app\common\service\order\Refund as RefundService;
use app\common\service\qrcode\Extract as ExtractQRcode;
use Guzzle\Tests\Mock\ErrorResponseMock;

/**
 * 拼团订单控制器
 * Class Order
 * @package app\api\controller
 */
class Order extends Controller
{
    /* @var \app\api\model\User $user */
    private $user;

    /* @var CheckoutValidate $validate */
    private $validate;

    /**
     * 构造方法
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    public function _initialize()
    {
        parent::_initialize();
        // 用户信息
        $this->user = $this->getUser();
        // 验证类
        $this->validate = new CheckoutValidate;
    }

    /**
     * 订单结算台
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \Exception
     */
    public function checkout()
    {
        // 实例化结算台服务
        $Checkout = new CheckoutModel;
        // 订单结算api参数
        $params = $Checkout->setParam($this->getParam([
            'goods_id' => 0,
            'goods_num' => 0,
            'goods_sku_id' => '',
        ]));
        // 表单验证
        if (!$this->validate->scene('buyNow')->check($params)) {
            return $this->renderError($this->validate->getError());
        }
        // 立即购买：获取订单商品列表
        $model = new OrderModel;
        $goodsList = $model->getOrderGoodsListByNow($params);
        // 获取订单确认信息
        $orderInfo = $Checkout->onCheckout($this->user, $goodsList);
        if ($this->request->isGet()) {
            return $this->renderSuccess($orderInfo);
        }
        // 订单结算提交
        if ($Checkout->hasError()) {
            return $this->renderError($Checkout->getError());
        }
        // 创建订单
        if (!$Checkout->createOrder($orderInfo)) {
            return $this->renderError($Checkout->getError() ?: '订单创建失败');
        }
        // 构建微信支付请求
        $payment = $model->onOrderPayment($this->user, $Checkout->model, $params['pay_type']);
        // 返回结算信息
        return $this->renderSuccess([
            'order_id' => $Checkout->model['order_id'],   // 订单id
            'pay_type' => $params['pay_type'],  // 支付方式
            'payment' => $payment               // 微信支付参数
        ], ['success' => '支付成功', 'error' => '订单未支付']);
    }

    /**
     * 订单结算提交的参数
     * @param array $define
     * @return array
     */
    private function getParam($define = [])
    {
        return array_merge($define, $this->request->param());
    }

    /**
     * 我的拼团订单列表
     * @param $dataType
     * @return array
     * @throws \think\exception\DbException
     */
    public function lists($dataType)
    {
        $model = new OrderModel;
        $list = $model->getList($this->user['user_id'], $dataType);
        return $this->renderSuccess(compact('list'));
    }

    /**
     * 拼团订单详情信息
     * @param $order_id
     * @return array
     * @throws \app\common\exception\BaseException
     */
    public function detail($order_id)
    {
        // 订单详情
        $model = OrderModel::getUserOrderDetail($order_id, $this->user['user_id']);
        // 该订单是否允许申请售后
        $model['isAllowRefund'] = $model->isAllowRefund();
        return $this->renderSuccess([
            'order' => $model,  // 订单详情
            'setting' => [
                // 积分名称
                'points_name' => SettingModel::getPointsName(),
            ],
        ]);
    }

    /**
     * 获取物流信息
     * @param $order_id
     * @return array
     * @throws \app\common\exception\BaseException
     */
    public function express($order_id)
    {
        // 订单信息
        $order = OrderModel::getUserOrderDetail($order_id, $this->user['user_id']);
        if (!$order['express_no']) {
            return $this->renderError('没有物流信息');
        }
        // 获取物流信息
        /* @var \app\store\model\Express $model */
        $model = $order['express'];
        $express = $model->dynamic($model['express_name'], $model['express_code'], $order['express_no']);
        if ($express === false) {
            return $this->renderError($model->getError());
        }
        return $this->renderSuccess(compact('express'));
    }

    /**
     * 取消订单
     * @param $order_id
     * @return array
     * @throws \app\common\exception\BaseException
     */
    public function cancel($order_id)
    {
        $model = OrderModel::getUserOrderDetail($order_id, $this->user['user_id']);
        if ($model->cancel($this->user)) {
            return $this->renderSuccess($model->getError() ?: '订单取消成功');
        }
        return $this->renderError($model->getError() ?: '订单取消失败');
    }

    /**
     * 确认收货
     * @param $order_id
     * @return array
     * @throws \app\common\exception\BaseException
     */
    public function receipt($order_id)
    {
        $model = OrderModel::getUserOrderDetail($order_id, $this->user['user_id']);
        if ($model->receipt()) {
            return $this->renderSuccess();
        }
        return $this->renderError($model->getError());
    }

    /**
     * 立即支付
     * @param int $order_id 订单id
     * @param int $payType 支付方式
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function pay($order_id, $payType = PayTypeEnum::WECHAT)
    {
        // 订单详情
        $model = OrderModel::getUserOrderDetail($order_id, $this->user['user_id']);
        // 订单支付事件
        if (!$model->onPay($payType)) {
            return $this->renderError($model->getError() ?: '订单支付失败');
        }
        // 构建微信支付请求
        $payment = $model->onOrderPayment($this->user, $model, $payType);
        // 支付状态提醒
        return $this->renderSuccess([
            'order_id' => $model['order_id'],   // 订单id
            'pay_type' => $payType,             // 支付方式
            'payment' => $payment               // 微信支付参数
        ], ['success' => '支付成功', 'error' => '订单未支付']);
    }

    /**
     * 获取订单核销二维码
     * @param $order_id
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    public function extractQrcode($order_id)
    {
        // 订单详情
        $order = OrderModel::getUserOrderDetail($order_id, $this->user['user_id']);
        // 判断是否为待核销订单
        if (!$order->checkExtractOrder($order)) {
            return $this->renderError($order->getError());
        }
        $Qrcode = new ExtractQRcode(
            $this->wxapp_id,
            $this->user,
            $order_id,
            OrderTypeEnum::SHARING
        );
        return $this->renderSuccess([
            'qrcode' => $Qrcode->getImage(),
        ]);
    }


    // TODO LLh 测试
    public function test()
    {
        $model = Active::detail(2);
        $model->onUpdate(2, 2);
    }

    // TODO LLh 发送红包跟退款
    public function red_bag()
    {
        try {
            do {
                $log = new RedBagLog;
                $data = $log->where("status", 1)->limit(50)->select()->toArray();
                if (empty($data)) {
                    echo date("Y-m-d H:i:s")."-没有符合条件的记录".PHP_EOL;
                    break;
                }
                $active_user = new ActiveUsers();
                $user_red = new UserRedBag();
                $service = new RefundService;
                $order = new \app\api\model\sharing\Order();
                $time = time();

                foreach ($data as $log_value) {
                    $active_id = $log_value['active_id'];
                    $award_money = $log_value['award_money'];
                    $win_people = $log_value['win_people'];

                    $win_user = []; // 中奖者
                    $loser_user = []; // 没中奖给予红包

                    $users = $active_user->where("active_id", $active_id)
                        ->field(["user_id", "order_id"])->select()->toArray();

                    // 打乱顺序
                    shuffle($users);

                    foreach ($users as $user) {
                        if ($win_people) {
                            $win_user[] = $user;
                            $win_people--;
                        } else {
                            $loser_user[] = $user;
                        }
                    }
                    if (!empty($loser_user)) {
                        // 给没中奖的用户  发送待领取红包,且退钱
                        $in_user = [];
                        $orderS = [];
                        foreach ($loser_user as $loserUser) {
                            $in_user[] = [
                                "award_money" => $award_money,
                                "active_id" => $active_id,
                                "user_id" => $loserUser['user_id'],
                                "order_id" => $loserUser['order_id'],
                                "create_time" => $time,
                                "update_time" => $time,
                            ];

                            $orderS[] = $loserUser['order_id'];
                        }
                        // LLH 订单状态修改
                        $order->whereIn("order_id", $orderS)->update(
                            ["order_status" => 88]
                        );
                        $user_red->insertAll($in_user);
                        // 退钱
                        foreach ($loser_user as $loserUser) {
                            // 发起退钱 放在后面执行
                            $orderM = $order->where("order_id", $loserUser['order_id'])->find();
                            $service->execute($orderM);
                            // 更新订单状态
                            $orderM->save([
                                'is_refund' => 1,
                            ]);
                        }
                    }

                    $log->where("id", $log_value['id'])->update(
                        ["status" => 2]
                    );
                }
            } while (0);
        } catch (\Exception $e) {
            var_dump($e->getMessage());
        }
    }

    // TODO LLh 可以提现
    public function canWithdraw()
    {
        try {
            do {
                $time = time();
                $cha_time = $time - 7 * 24 * 3600; // 七天前红包更改为可以提现
                $cha_time = $time; // 七天前红包更改为可以提现
                $redBag = new UserRedBag;
                $user = new User();
                $BalanceLog = new BalanceLog();
                $data = $redBag->where("status", 1)
                    ->where("create_time", "<=", $cha_time)
                    ->limit(50)->select()->toArray();

                if (empty($data)) {
                    echo date("Y-m-d H:i:s")."-没有符合条件的记录".PHP_EOL;
                    break;
                }
                foreach ($data as $val) {
                    $redBag->where("id", $val['id'])->update([
                        "status" => 2,
                        "update_time" => $time,
                    ]);
                    $user->where("user_id", $val['user_id'])->setInc("balance", $val['award_money']);

                    $BalanceLog->insert([
                        "user_id" => $val['user_id'],
                        "scene" => 50,
                        "money" => $val['award_money'],
                        "describe" => "拼单:".$val["order_id"]."奖励红包",
                        "create_time" => $time,
                    ]);
                }

            } while (0);
        } catch (\Exception $e) {
            var_dump($e->getMessage());
        }
    }

}
